16. Sending Extras to IntentService

Sending Extras to IntentService

The main change we will be doing in this exercise is replacing the Water All Plants action with a more specific Water Plant one. This will water an individual plant given its ID instead of watering all the plants in the garden.

To be able to water a specific plant you will need to launch the same IntentService but will also need to pass the Plant ID with it.

To do so, once you create the wateringIntent that will launch the PlantWateringService, you can use the method putExtra() where you can set a name and a value just like you would for any normal Intent.

Intent wateringIntent = new Intent(context, PlantWateringService.class);
wateringIntent.setAction(PlantWateringService.ACTION_WATER_PLANT);
wateringIntent.putExtra(PlantWateringService.EXTRA_PLANT_ID, plantId);
PendingIntent wateringPendingIntent = PendingIntent.getService(context, 0, wateringIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_water_button, wateringPendingIntent);

In this exercise, the goal is to complete the following changes in My Garden app:

1) Change the water-all click event in the widget to water only that specific plant shown which involves

  • Add the plantId as a new parameter to the updatePlantWidgets method
  • Change the watering service action from ACTION_WATER_PLANTS to ACTION_WATER_PLANT
  • Change the update query to use a SINGLE_PLANT_URI
  • Define and using EXTRA_PLANT_ID to pass the plant ID to the intent service from the widget
  • Call putExtra and passing the plantId when creating the pending intent for the watering service
  • Call getLongExtra to extract the plnatId in the service
  • Make sure you update the widgets after watering by calling startActionUpdatePlantWidgets

2) Hide the water drop button in the widget if it’s been less than MIN_AGE_BETWEEN_WATER since it was last watered

  • Add a new boolean parameter to updatePlantWidgets to indicate if the plant can be watered or not
  • Use setViewVisibility to change the widget_water_button Visibility from View.VISIBLE to View.INVISIBLE to hide it

3) Change the widget plant image click handler to launch the Detail Activity for that plant rather than the Main Activity

  • If plantId was INVALID_PLANT_ID, then launch the MainActivity as usual
  • Otherwise launch the PlantDetailActivity passing in the plantId as EXTRA_PLANT_ID

4) Add a TextView underneath the plant image that displays the plant ID in both the main activity as well as in the widget to help identify each plant